<template>
  <div style="display: flex;justify-content: center;align-items: center">
    <div style="height: 400px;width: 400px;border: 1px solid #ccc;display: flex;justify-content: center;">
      <div class="clearfix">
        <a-upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
          <a-button>
            <upload-outlined></upload-outlined>
            Select File
          </a-button>
        </a-upload>
        <a-button
            type="primary"
            :disabled="fileList.length === 0"
            :loading="uploading"
            style="margin-top: 16px"
            @click="handleUpload"
        >
          {{ uploading ? 'Uploading' : 'Start Upload' }}
        </a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import request from 'umi-request';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadProps } from 'ant-design-vue';
import CryptoJS from 'crypto-js';
const fileList = ref<UploadProps['fileList']>([]);
const uploading = ref<boolean>(false);

const handleRemove: UploadProps['onRemove'] = file => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

const beforeUpload: UploadProps['beforeUpload'] = async file => {
  fileList.value = [...(fileList.value || []), file];
  fileList.value.forEach((file: UploadProps['fileList'][number]) => {
    console.log("文件名称：" + file.name);
  });

  // 创建一个 FileReader 对象来读取文件内容
  const reader = new FileReader();

  // 返回一个 Promise 来处理文件读取完成的事件
  const readFile = () => {
    return new Promise((resolve, reject) => {
      reader.onload = () => {
        // 读取完成后，获取文件的二进制数据
        const fileData = reader.result as ArrayBuffer;
        // 将二进制数据转换为 WordArray
        const wordArray = CryptoJS.lib.WordArray.create(fileData);
        // 计算 MD5 值
        const md5 = CryptoJS.MD5(wordArray).toString();
        // 打印文件名称和 MD5 值
        console.log(`文件名称：${file.name}，MD5 值：${md5}`);
        resolve(md5);
      };

      reader.onerror = () => {
        // 读取失败时，打印错误信息并拒绝 Promise
        console.error('文件读取失败');
        reject(new Error('文件读取失败'));
      };

      // 以二进制格式读取文件
      reader.readAsArrayBuffer(file);
    });
  };

  try {
    // 等待文件读取完成并计算 MD5 值
    await readFile();
  } catch (error) {
    // 处理读取文件时的错误
    console.error('计算 MD5 值时出错:', error);
  }

  return false;
};

const handleUpload = () => {
  const formData = new FormData();
  fileList.value.forEach((file: UploadProps['fileList'][number]) => {
    formData.append('files[]', file as any);
  });
  uploading.value = true;

  // You can use any AJAX library you like
  request('http://localhost:8080/test/upload', {
    method: 'post',
    data: formData,
  })
      .then(() => {
        fileList.value = [];
        uploading.value = false;
        message.success('upload successfully.');
      })
      .catch(() => {
        uploading.value = false;
        message.error('upload failed.');
      });
};
</script>
